<template>
	<div class="login">
		<div class="top">
			<span class="title">{{ title }}</span>
			<i @click="close" class="icon"></i>
		</div>
		<div class="middle">
			<a-form
				:layout="formState.layout"
				ref="formRef"
				:model="formState"
				:rules="rules"
			>
				<a-form-item
					:label="$t('personalCenter.currentPassword', '登录密码')"
					name="password"
				>
					<a-input-password
						class="iputStyle"
						v-model:value="formState.password"
						type="password"
						:placeholder="
							$t(
								'personalCenter.enterPwd',
								'请输入当前密码'
							)
						"
					/>
				</a-form-item>
				<a-form-item
					:label="$t('personalCenter.changePhone', '您要换绑的新手机号')"
					name="phoneNum"
				>
					<a-input
						class="phone"
						v-model:value="formState.phoneNum"
						:placeholder="$t('personalCenter.enterPhone', '请输入新手机号')"
					/>
				</a-form-item>
				<a-form-item :label="$t('personalCenter.verificationCode', '验证码')" name="code">
					<!-- <a-input-password
						v-model:value="formState.confirmPassword"
						type="password"
						:placeholder="
							$t('personalCenter.pleaseEnterConfirmPassword', '请输入确认密码')
						"
					/> -->
					<div class="code_all">
						<input
							class="code_phone"
							v-model="formState.code"
							:placeholder="$t('personalCenter.verificationCode', '请输入验证码')"
						/>
						<button
							class="code_submit"
							:disabled="requestDisabled"
							@click="getCode"
						>
							{{ requestDisabled ? restTime+'s' : $t('personalCenter.getVerificationCode', '获取验证码') }}
						</button>
					</div>
				</a-form-item>
			</a-form>
		</div>
		<div class="bottom">
			<button class="cancel" @click="close">{{ $t('personalCenter.cancel', '取消') }}</button>
			<button class="bind" @click="onSubmit">{{ $t('personalCenter.confirm', '确认') }}</button>
		</div>
	</div>
</template>
<script lang="ts">
import {
	defineComponent,
	ref,
	watch,
	onMounted,
	reactive,
	createVNode,
} from 'vue'
import { apiInit } from '@/services'
import { useStore } from 'vuex'
import { i18n } from '@/locales'
import md5 from 'md5'
const { $t } = i18n
import message from 'ant-design-vue/lib/message'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
export default defineComponent({
	props: {
		title: {
			type: String,
			default: '修改组织登录密码',
		},
		originPhone: {
			type:Number
		}
	},
	setup(props, ctx) {
		const api = apiInit()
		const formRef = ref()
		// const isShow: any = ref(true)
		let formState: any = reactive({
			layout: 'vertical',
			password: '',
			phoneNum: '',
			code: '',
			tenant_id: '',
			tenant_user_id:''
		})
		const store = useStore()
		// 手机验证码
		const requestDisabled = ref(false)
		const restTime = ref(59)
		const originalPhone = ref('')

		// 对话框
		const showConfirm = () => {
			Modal.confirm({
				title: $t('personalCenter.sure',
					'确定要换绑吗？'),
				icon: createVNode(ExclamationCircleOutlined),
				// content: `手机号将从${originalPhone.value}替换为${formState.phoneNum}?`,
				content:`${$t('personalCenter.replace','手机号将从')+originalPhone.value+$t('personalCenter.to','替换为')+formState.phoneNum}`,

				async onOk() {
					const result: any = await api.default.UpdatePhoneUserCenterPrivateV1POST({
						payload: {
							code: formState.code,
							phone: formState.phoneNum,
							pwd: md5(formState.password),
							user_id: store.state.centerUser.user_base_info.user_id,
							tenant_id: formState.tenant_id,
							tenant_user_id: formState.tenant_user_id,
						} as any,
					})

					if (result.state == 'SUCCESS') {
						// ctx.emit('close', false)
						// ctx.emit('Refresh')
						message.success(
							$t('personalCenter.successfullyChanged', '换绑手机号成功'),
							3
						),
							(formState = {
								phoneNum: '',
								code: '',
							})
                            // let newTime = +sessionStorage.getItem('beginTimeChangeBind')!
							// newTime-=61000
							// sessionStorage.setItem('beginTime',newTime+'')
						window.location.reload()
						ctx.emit("changeBindFlag")
					}
					if (result.state === 'FAIL') {
						message.error(result.message, 3)
						// ctx.emit('showTip', { msg: result.message, type: 'error' })
					}
				},

				onCancel() {
					console.log('Cancel')
				},

				class: 'test',
			})
		}
		// 提交数据
		const onSubmit = () => {
			formRef.value
				.validate()
				.then(() => {
					showConfirm()
				})
				.catch((error: any) => {
					return false
				})
		}

		// 手机号校验
		const phoneNumValidate = (rule: any, value: any, callback: any) => {
			const newFalg = originalPhone.value !== formState.phoneNum
			// const newFalg = /^1[3|4|5|7|8][0-9]\d{4,8}$/.test(formState.phoneNum)
			if (newFalg) {
				callback()
			} else {
				callback(
					new Error($t('personalCenter.inconsistent', '手机号与源手机号一致'))
				)
			}
		}

		const rules = {
			password: [
				{
					required: true,
					message: $t(
						'personalCenter.pleaseEnterTheCurrentPassword',
						'请输入当前登录密码'
					),
					trigger: 'blur',
				},
				// {
				// 	validator: passwordValidate,
				// 	trigger: 'blur',
				// },
			],
			phoneNum: [
				{
					required: true,
					message: $t(
						'personalCenter.enterPhone',
						'请输入新手机号'
					),
					trigger: 'blur',
				},
				{
					validator: phoneNumValidate,
					trigger: 'blur',
				},
			],
			// code: [
			//     {
			//         required: true,
			//         message: $t('personalCenter.pleaseEnterNewPassword', ''),
			//     }
			// ]
		}

		const getCode = () => {
			formRef.value.validate().then(async () => {
				const smsCode = await api.default.SendSmsUserCenterPrivateV1POST({
					query: {
						bizType: 'UPDATE_PHONE',
						phone: formState.phoneNum,
					},
				})
				if(smsCode.code === '000000'){
						restTime.value = 59
						const timer = setInterval(()=> {
							if(restTime.value> 0) {
								requestDisabled.value = true
								restTime.value--
							}else{
								requestDisabled.value =false
								clearInterval(timer)
								
							}
						},1000)
					}
					requestDisabled.value = true
					if(smsCode.code !== '000000') {
						message.error(smsCode.message as any, 1.5)
						requestDisabled.value = false
					}
				// if(smsCode.code !== '000000') {
				// 		message.error(smsCode.msg as any, 1.5)
				// 	}
				// requestDisabled.value = true
				// let beginTime: any = new Date().getTime()
				// // sessionStorage.setItem('beginTimeChangeBind', beginTime)
				// observeTime(beginTime)
			})
		}
		// 监听请求验证码的剩余时间
		// const observeTime = (beginTime: any) => {
		// 	const timer = setInterval(() => {
		// 		let curTime = new Date().getTime()
		// 		restTime.value = `${Math.round(59 - (curTime - beginTime) / 1000)}s`
		// 		if (parseInt(restTime.value) < 0) {
		// 			requestDisabled.value = false
		// 			restTime.value = '59s'
		// 			clearInterval(timer)
		// 		}
		// 	}, 1000)
		// }
		//关闭
		const close = () => {
			ctx.emit('close', false)
		}

		onMounted(() => {
			formState.tenant_user_id = store.state.userInfo.employee_id
			formState.tenant_id = store.state.tenant.tenant_id
			originalPhone.value = store.state.centerUser.user_base_info.phone
		})

		return {
			formRef,
			// isShow,
			formState,
			close,
			rules,
			onSubmit,
			getCode,
			// observeTime,
			showConfirm,
			requestDisabled,
			restTime,
			originalPhone,
			// CheckPwdIsNullUser
		}
	},
})
</script>
<style lang="less" scoped>
.login {
	width: 349px;
	// height: 414px;
	background: #ffffff;
	border-radius: 8px;
	overflow: hidden;
	.top {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 50px;
		line-height: 50px;
		background: var(--bl-brand-c);
		padding: 0 15px;
		box-sizing: border-box;
		.title {
			font-family: 'PingFang SC';
			font-style: normal;
			font-weight: 500;
			font-size: 16px;
			color: #ffffff;
		}
		.icon {
			width: 23px;
			height: 23px;
			background-image: url(/public/icon/close.svg);
			cursor: pointer;
		}
	}
	.middle {
		padding: 25px 27px 0 23px;
		.code_all {
			display: flex;
			justify-content: space-between;
			width: 300px;
			height: 40px;
			line-height: 40px;
			border: 1px solid #ccc;
			border-radius: 5px;
			overflow: hidden;
			.code_phone {
				width:173px;
				padding-left: 10px;
				border: none;
				outline: none;
			}
			.code_submit {
				padding-right: 15px;
				background-color: #ffffff;
				font-family: PingFang SC;
				font-style: normal;
				font-weight: 500;
				font-size: 14px;
				color: var(--bl-brand-c);
				cursor: pointer;
				outline: none;
				border: none;
			}
		}
	}
	.bottom {
		margin-bottom: 24px;
		display: flex;
		justify-content: flex-end;
		.cancel {
			// width: 62.17px;
			padding:0 17px;
			height: 32px;
			line-height: 32px;
			background: #ffffff;
			border: 1px solid #e8eaed;
			box-sizing: border-box;
			border-radius: 4px;
			text-align: center;
			font-family: PingFang SC;
			font-style: normal;
			font-weight: 500;
			font-size: 14px;
			margin-right: 12px;
			color: #1f2329;
			cursor: pointer;
		}
		.bind {
			// width: 62px;
			padding:0 17px;
			height: 32px;
			line-height: 32px;
			text-align: center;
			background: var(--bl-brand-c);
			border-radius: 4px;
			font-family: PingFang SC;
			font-style: normal;
			font-weight: 500;
			font-size: 14px;
			margin-right: 26px;
			color: #ffffff;
			cursor: pointer;
			border: 0;
		}
	}

	::v-deep .ant-form-item-control {
		// margin-bottom: 26px;
		&.has-error {
			height: 66px;
			margin: 0;
		}

	}
	::v-deep .ant-form-item-explain-error {
		font-size: 12px;
	}
	::v-deep .ant-form-item-required {
		font-family: 'PingFang SC';
		font-style: normal;
		font-weight: 400;
		font-size: 14px;
		line-height: 20px;
		color: #1f2329;
	}
	::v-deep .ant-input-password {
		height: 40px;
	}
	::v-deep .ant-form-item {
		padding-bottom: 0px;
	}
	::v-deep .ant-form-explain,
	.ant-form-item-control {
		position: absolute;
	}
	::v-deep .ant-form-item-label {
		font-weight: 400;
	}
	.phone {
		height: 40px;
	}
	.code {
		font-weight: 400;
	}
}
</style>